using NHibernate;
using TelerikMvcGridCustomBindingHelper.NHibernate.Exceptions;
using TelerikMvcGridCustomBindingHelper.ORMIntegration;
using TelerikMvcGridCustomBindingHelper.Util;

namespace TelerikMvcGridCustomBindingHelper.NHibernate.ORMIntegration
{
    internal class NHibernateIntegrationHolder : ORMIntegrationHolder
    {
        public IQueryOver<TEntity, TEntity> QueryOver<TEntity>() where TEntity : class
        {
            var nHibernateIntegration = ORMIntegration as INHibernateIntegration;

            Contract.Expect(() => nHibernateIntegration)
                .Throw(new NHibernateIntegrationException("Failed to locate or instatiate an NHibernate integration object."))
                .WhenViolate.IsNotNull();

            // ReSharper disable PossibleNullReferenceException
            var query = nHibernateIntegration.QueryOver<TEntity>();
            // ReSharper restore PossibleNullReferenceException

            Contract.Expect(() => nHibernateIntegration)
                .Throw(new NHibernateIntegrationException("Failed to create a QueryOver object."))
                .WhenViolate.IsNotNull();

            return query;
        }
    }
}